package com.project.service.impl;


import com.common.api.ApprovalApi;
import com.common.utils.uuid.IdUtils;
import com.framework.handler.MyMetaObjectHandler;
import com.project.comom.NumberDealUtils;
import com.project.domain.dto.projectCheckDto.*;
import com.project.domain.entity.BizCheckLog;
import com.project.domain.entity.BizReviewPlan;
import com.project.domain.entity.MyConstants;
import com.project.domain.vo.BizProjectApplyInfoVo;
import com.project.mapper.ProjectCheckMapper;
import com.project.service.IProjectCheckService;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

import static com.project.comom.DateDealUtils.castInputDateStrToRequireFormat;

/**
 * Created by cw13031 on 2025/2/6.
 * Description:
 */
@Service
public class ProjectCheckServiceImpl implements IProjectCheckService {

    @Autowired
    ProjectCheckMapper projectCheckMapper;

    @Autowired
    private MyMetaObjectHandler autoFillFieldsHandler;

    @Autowired
    private ApprovalApi approvalApi;

    @Override
    public List<HashMap<String, Object>> search(SearchReqDto dto) {
        changeInputDateFormat(dto);
        changeInputFeeFormat(dto);
        List<HashMap<String, Object>> list = projectCheckMapper.search(dto);
        // 补充字段
        addFields(list);
        //region 添加文件下载字段
        addFileFields(list);
        //endregion
        //region 元-->万元
        NumberDealUtils.mapListYuan2Wan(list,"applyFee");
        //endregion
        return list;
    }

    @Override
    public List<HashMap<String, Integer>> searchStatistics(SearchReqDto dto) {
        changeInputDateFormat(dto);
        changeInputFeeFormat(dto);
        return projectCheckMapper.searchStatistics(dto);
    }

    /**
     *
     * @param bizCheckLog x
     * @return x
     * @deprecated 该方法已被废弃，由于接入了流程引擎，审核日志由该模块自动处理，因此该接口不再会被调用。
     */
    @Override
    @Deprecated
    public int changeCheckState(BizCheckLog bizCheckLog) {
        int rows;
        if (!StringUtils.hasText(bizCheckLog.getId())){
            // 数据 插入时 自动记录的字段
            MetaObject metaObject = MyMetaObjectHandler.getMetaObject(bizCheckLog);
            autoFillFieldsHandler.fillForInsert(metaObject);
            //生成主键id
            String uuid = IdUtils.simpleUUID();
            bizCheckLog.setId(uuid);
            rows = projectCheckMapper.insertBizCheckLog(bizCheckLog);
        }else {
            // 数据 更新时 自动记录的字段
            MetaObject metaObject = MyMetaObjectHandler.getMetaObject(bizCheckLog);
            autoFillFieldsHandler.fillForUpdate(metaObject);
            rows = projectCheckMapper.updateBizCheckLog(bizCheckLog);
        }
        return rows;
    }

    @Override
    public int changeProjectState(LixiangActionReqDto dto) {
        return projectCheckMapper.changeProjectState(dto);
    }

    @Override
    public ArrayList<BookCheckHistoryResDto> getCheckHistoryByBookId(String bookId) {
        return projectCheckMapper.getCheckHistoryByBookId(bookId);
    }

    @Override
    public int updateProjectId(String bookId, String projectId) {
        return projectCheckMapper.updateProjectId(bookId,projectId);
    }

    @Override
    public int review(BizReviewPlan plan) {
        int rows;
        if (!StringUtils.hasText(plan.getId())){
            // 数据 插入时 自动记录的字段
            MetaObject metaObject = MyMetaObjectHandler.getMetaObject(plan);
            autoFillFieldsHandler.fillForInsert(metaObject);
            //生成主键id
            String uuid = IdUtils.simpleUUID();
            plan.setId(uuid);
            rows = projectCheckMapper.insertReviewPlan(plan);
        }else {
            // 数据 更新时 自动记录的字段
            MetaObject metaObject = MyMetaObjectHandler.getMetaObject(plan);
            autoFillFieldsHandler.fillForUpdate(metaObject);
            rows = projectCheckMapper.updateReviewPlan(plan);
        }
        return rows;
    }

    @Override
    public HashMap<String, Object> getReviewPlanById(String planId) {
        return projectCheckMapper.getReviewPlanById(planId);
    }

    @Override
    public ArrayList<MsgListResDto> msgList(MsgListReqDto dto) {
        return projectCheckMapper.msgList(dto);
    }

    @Override
    public MsgDetailResDto msgDetail(MsgDetailReqDto dto) {
        return projectCheckMapper.msgDetail(dto);
    }

    /**
     * 该list接口的后续操作涉及到审核相关，
     * 因此需要额外返回字段
     */

    public void addFields(List<HashMap<String, Object>> list){
        //获取当前用户所有的代办列表
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(MyConstants.MODULE_NAME);

        for (HashMap<String, Object> item : list) {

            String processInstanceId = item.get("processInstanceId") != null
                    ? item.get("processInstanceId").toString()
                    : "";
            // 判断是否是审核人，并设置taskId
            if (com.common.utils.StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
                item.put("taskId",instanceTaskMap.get(processInstanceId));
                item.put("isAuditor",true);
            } else {
                item.put("taskId","");
                item.put("isAuditor",false);
            }
        }

    }

    /**
     * 页面有下载功能，因此需要查到book的文件，返回给前端
     * 由于不希望对原有主表查询sql进行大改，因此采用额外一次查询+遍历方式，给每个book加上文件信息
     * @param list 符合条件的book列表
     */
    public void addFileFields(List<HashMap<String, Object>> list){
        // region 获取列表中所有 book 的 fileId（fileId用逗号分隔）
        Set<String> fileIdSet = new HashSet<>();
        for (HashMap<String, Object> obj : list) {
            Object uploadFileIdObj = obj.get("uploadFileId");
            if (uploadFileIdObj != null) {
                String[] ids = uploadFileIdObj.toString().split(",");
                for (String id : ids) {
                    if (!id.trim().isEmpty()) {
                        fileIdSet.add(id.trim());
                    }
                }
            }
        }
        // endregion
        //region 用所有fileId查询文件名称
        List<HashMap<String, String>> fileMappingList = new ArrayList<>();

        if (!fileIdSet.isEmpty()) {
            fileMappingList = projectCheckMapper.getFileInfoByFileIds(new ArrayList<>(fileIdSet));
        }
        //endregion

        //region 通过查询得到的file信息，构建映射表
        Map<String, HashMap<String, String>> fileMappingMap = new HashMap<>();
        for (HashMap<String, String> file : fileMappingList) {
            fileMappingMap.put(file.get("id"), file);
        }
        //endregion

        //region 再次遍历book列表，给每个book加上文件信息
        for (HashMap<String, Object> resItem : list) {
            List<HashMap<String, String>> fileInfoList = new ArrayList<>();

            Object uploadFileIdObj = resItem.get("uploadFileId");
            if (uploadFileIdObj != null) {
                String[] ids = uploadFileIdObj.toString().split(",");
                for (String id : ids) {
                    id = id.trim();
                    if (fileMappingMap.containsKey(id)) {
                        fileInfoList.add(fileMappingMap.get(id));
                    }
                }
            }
            resItem.put("fileInfo", fileInfoList);
        }
        //endregion

    }


    void changeInputDateFormat(SearchReqDto dto) {
        dto.setApplyDate1(castInputDateStrToRequireFormat(dto.getApplyDate1()));
        dto.setApplyDate2(castInputDateStrToRequireFormat(dto.getApplyDate2()));
    }

    void changeInputFeeFormat(SearchReqDto dto) {
        if (dto.getMinFee()!=null){
            dto.setMinFee(NumberDealUtils.multiply_bigDecimal(dto.getMinFee()));
        }

        if (dto.getMaxFee()!=null){
            dto.setMaxFee(NumberDealUtils.multiply_bigDecimal(dto.getMaxFee()));
        }
    }
}
